package cn.john.hrm.service.impl;

import cn.john.hrm.LoginUserConstant;
import cn.john.hrm.constant.RegistConstant;
import cn.john.hrm.domain.LoginUser;
import cn.john.hrm.domain.VipUser;
import cn.john.hrm.dto.RegistDto;
import cn.john.hrm.feign.LoginUserFeignClient;
import cn.john.hrm.mapper.VipUserMapper;
import cn.john.hrm.service.IVipUserService;
import cn.john.hrm.util.AjaxResult;
import cn.john.hrm.util.BitStatesUtils;
import cn.john.hrm.util.ValidUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.validation.Valid;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author john
 * @since 2021-06-25
 */
@Service
public class VipUserServiceImpl extends ServiceImpl<VipUserMapper, VipUser> implements IVipUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LoginUserFeignClient userFeignClient;
    @Autowired
    private VipUserMapper vipUserMapper;

    @Override
    public AjaxResult register(@Valid RegistDto registDto) {
        // 参数校验交给jsr303
        // 校验手机验证码
        String key = RegistConstant.REGIST_KEY + "::" + registDto.getMobile();
        Object obj = redisTemplate.opsForValue().get(key);
        ValidUtils.assertNotNull(obj, "手机验证码已经失效");
        String code = obj.toString();
        String smsCode = registDto.getSmsCode().trim();
        if(!code.equals(smsCode)) {
            throw new RuntimeException("手机号验证码有误!请重新输入!");
        }
        // 校验通过 保存用户信息到数据库 保存到auth服务的t_login_user 保存到t_vip_user
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(registDto.getMobile());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        loginUser.setPassword(encoder.encode(registDto.getPassword()));
        loginUser.setType(LoginUserConstant.LOGIN_GENERAL);
        AjaxResult result = userFeignClient.addOrUpdate(loginUser);
        // 判断auth是否保存成功
        if (!result.isSuccess()) {
            throw new RuntimeException("注册失败!");
        }
        Integer loginId = (Integer) result.getResultObj();
        // 保存t_vip_user
        VipUser vipUser = new VipUser();
        vipUser.setPhone(registDto.getMobile());
        vipUser.setPassword(registDto.getPassword());
        long date = System.currentTimeMillis();
        vipUser.setCreateTime(date);
        vipUser.setLoginId(Long.valueOf(loginId));
        // 单独处理状态
        long state = BitStatesUtils.OP_REGISTED;
        state = BitStatesUtils.addState(state, BitStatesUtils.OP_ACTIVED);
        state = BitStatesUtils.addState(state, BitStatesUtils.OP_AUTHED_PHONE);
        vipUser.setBitState(state);
        vipUserMapper.insert(vipUser);
        return result;
    }
}
